package com.yc.net.socket;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.util.Arrays;
import java.util.Scanner;

public class QQClient {

    static Scanner sc = new Scanner(System.in);
    public static void main(String[] args) throws IOException, InterruptedException {
        // 创建即连接
        Socket socket =  new Socket("127.0.0.1",8888);
        // 输出地址信息
        InetAddress inetAddress = socket.getInetAddress();
        System.out.println("inetAddress.getHostAddress() = " + inetAddress.getHostAddress());
        System.out.println("inetAddress.getAddress() = " + Arrays.toString(inetAddress.getAddress()));
        // 获取输入输出流
        InputStream in = socket.getInputStream();
        OutputStream out = socket.getOutputStream();

        Thread t1 = new Thread(()->{
            boolean running = true;
            while(running){
                System.out.print("请输入：");
                String msg = sc.nextLine();
                try {
                    out.write(msg.getBytes());
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        });

        Thread t2 = new Thread(()->{
            boolean running = true;
            while(running){
                byte[] bytes = new byte[1024];
                int count;
                try {
                    count = in.read(bytes);
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
                System.out.println("服务端说：" + new String(bytes,0,count));
            }
        });

        t1.start();
        t2.start();

        t1.join();
        t2.join();

        socket.close();

    }
}
